package handler

import (
	"encoding/json"
	"food-hub/cache"
	"food-hub/model"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
)

func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.Query("page"))
	size, _ := strconv.Atoi(c.Query("size"))
	offset := (page - 1) * size
	var total int64
	var order []model.Order
	redis_key := "order_list_" + strconv.Itoa(page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Offset(offset).Limit(size).Find(&order)
		jsonData, _ := json.Marshal(order)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &order)
	}
	model.DB.Model(&order).Count(&total)
	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "ok",
		"data":  order,
		"total": total,
	})
	return
}
func Detail(c *gin.Context) {
	id, _ := strconv.Atoi(c.Query("id"))
	var order model.Order
	redis_key := "order_list_detail_" + strconv.Itoa(id)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Where("id=?", id).Find(&order)
		jsonData, _ := json.Marshal(order)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &order)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "ok",
		"data": order,
	})
	return
}
func Add(c *gin.Context) {
	name := c.PostForm("name")
	content := c.PostForm("content")
	if name == "" || content == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不能空",
		})
		return
	}
	data := model.Order{
		Name:    name,
		Content: content,
	}
	if err := model.DB.Create(&data).Error; err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "失败",
		})
		return
	}
	var order model.Order
	redis_key := "order_" + strconv.Itoa(int(data.ID))
	model.DB.Where("id=?", data.ID).Find(&order)
	jsonData, _ := json.Marshal(data)
	cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "ok",
		"data": data,
	})
	return
}
